package com.kuiniu.threeframe.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuiniu.threeframe.Address;
import com.kuiniu.threeframe.client.Client;
import com.kuiniu.threeframe.client.EventListener;
import com.kuiniu.threeframe.client.entity.Message;
import com.kuiniu.threeframe.server.entity.ReceiveBody;
import com.kuiniu.threeframe.server.entity.SendBody;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.HashMap;
import java.util.Map;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("接收websocket连接:" + ctx.channel().remoteAddress().toString());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("关闭websocket连接:" + ctx.channel().remoteAddress().toString());
        SocketMapper.getInstance().removeChannel(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();

            Map paramMap = getUrlParams(uri);
            System.out.println("接收到的参数是：" + JSON.toJSONString(paramMap));
            //如果url包含参数，需要处理
            if (uri.contains("?")) {
                String newUri = uri.substring(0, uri.indexOf("?"));
                System.out.println(newUri);
                request.setUri(newUri);
            }

        } else if (msg instanceof TextWebSocketFrame) {
            //正常的TEXT消息类型
            TextWebSocketFrame frame = (TextWebSocketFrame) msg;
            System.out.println("接收到websocket客户端数据:" + frame.text());
            String TextMsg = frame.text();
            ReceiveBody body = JSON.parseObject(TextMsg, ReceiveBody.class);
            if (body != null) {
                String host = body.getUrl();
                if (host != null) {
                    Client client = SocketMapper.getInstance().getClient(host);
                    switch (body.getCode()) {
                        case "1":
                            Address address = new Address(host, body.getPort());
                            if (client == null) {
                                connectToServerWithAddress(ctx, address);
                            } else {
                                addListener(ctx, address, client);
                            }
                            break;
                        case "2":

                            break;
                        default:
                            if (client != null) {
                                client.sendMsg(new Message(body.getCode(), body.getData()), true);
                            }
                            break;
                    }
                }
            }
        }
        super.channelRead(ctx, msg);
    }

    private void connectToServerWithAddress(ChannelHandlerContext ctx, Address address) {
        Client client = new Client.Builder()
                .address(address)
                .build();
        addListener(ctx, address, client);
        SocketMapper.getInstance().addChannelWithClient(ctx, client);
    }

    private void addListener(ChannelHandlerContext ctx, Address address, Client client) {
        SendBody body = new SendBody();
        body.setHost(address.getUrl());
        client.addListener(new EventListener() {
            @Override
            public void onMessage(Message message) {
                String str = JSONObject.toJSONString(message);
                body.setCode(message.getCode());
                body.setMsg("数据接收成功");
                body.setData(message.getData());
                System.out.println("接收到socket服务端" + address.getUrl() + "数据:"
                        + str);
                ctx.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(body)));
            }

            @Override
            public void onConnected() {
                System.out.println("socket服务端" + address.getUrl() + "连接成功");
                body.setCode("1");
                body.setMsg("连接成功");
                body.setData(null);
                ctx.writeAndFlush(ctx.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(body))));
            }

            @Override
            public void onDisconnected() {
                System.out.println("socket服务端" + address.getUrl() + "断开连接");
                body.setCode("2");
                body.setMsg("连接失败");
                body.setData(null);
                ctx.writeAndFlush(ctx.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(body))));
            }
        });
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
    }

    private static Map getUrlParams(String url) {
        Map<String, String> map = new HashMap<>();
        url = url.replace("?", ";");
        if (!url.contains(";")) {
            return map;
        }
        if (url.split(";").length > 0) {
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr) {
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key, value);
            }
            return map;

        } else {
            return map;
        }
    }


}
